﻿package problems.readerswriters;

import problems.BenchmarkSemaphore;
import helpers.IAction;

public class ReaderWriterSolution implements IReaderWriter
{
    private final LightSwitch readLightSwitch;
    private final BenchmarkSemaphore roomEmpty;
    private final BenchmarkSemaphore turnstile;
    
    public ReaderWriterSolution()
    {
        readLightSwitch = new LightSwitch();
        roomEmpty = new BenchmarkSemaphore(1);
        turnstile = new BenchmarkSemaphore(1);
    }

    public void write(IAction action)
    {
        turnstile.waitOne();
        roomEmpty.waitOne();
        action.invoke();
        turnstile.release();
        roomEmpty.release();
    }

    public void read(IAction action)
    {
        turnstile.waitOne();
        turnstile.release();
        readLightSwitch.lock(roomEmpty);
        action.invoke();
        readLightSwitch.unlock(roomEmpty);
    }
}